//
//  PictureViewController.m
//  DesighBook
//
//  Created by 梅明 on 15/9/14.
//  Copyright (c) 2015年 梅明. All rights reserved.
//

#import "PictureViewController.h"
#import "HttpRequestManager.h"
#import "UIButton+setbutton.h"
#import "MypopViewController.h"
#import "SelectButtonView.h"
#import "DesighModel.h"
#import "CollectionViewCell.h"
#import "UIImageView+AFNetworking.h"
#import "MJRefresh.h"
#import "NotfoundView.h"
#import "SecondScrollDetailViewController.h"


#define viewwidth self.view.frame.size.width

@interface PictureViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,MJRefreshBaseViewDelegate>
{
    NSMutableArray *_dataArray;  //collectionview数据源
    BOOL _isSelect1;   //家装选择属性
    BOOL _isSelect2;   //工装选择属性
    BOOL _isDragDown;  //Refresh下拉属性
    UIButton *_buttonSpace1;  //家装 空间button
    UIButton *_buttonSytle;   //家装 style button
    UIButton *_buttonSpace2;  //工装 空间button
    int _page;
    NotfoundView *_notfoundview;  //没有搜到结果显示view
    UIView *_backBlackView;        //门板效果biew
    SelectButtonView *_buttonView; //显示button列表的view
    NSArray *_buttonArray1;  //第一个button选项了列表
    NSArray *_buttonArray2;  //第二个button选项了列表
    NSArray *_buttonArray3;  //第三个button选项了列表
    
    MJRefreshFooterView *_footView;  //底部视图
    MJRefreshHeaderView *_headView;  //头部视图
}
@property (weak, nonatomic) IBOutlet UIButton *button1; //家装按钮
@property (weak, nonatomic) IBOutlet UIButton *button2;  //工装按钮
@property (weak, nonatomic) IBOutlet UIView *view1;  //放家装按钮的view
@property (weak, nonatomic) IBOutlet UIView *view2;  //放工装按钮的view
@property (weak, nonatomic) IBOutlet UIView *view3;  //放空间,style按钮的view
@property (weak, nonatomic) IBOutlet UICollectionView *myCllectionView;

@end

@implementation PictureViewController
- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        _dataArray = [[NSMutableArray alloc]init];
        _isSelect1 = YES;
        _isSelect2 = NO;
        _page = 1;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setThreeButton]; //添加空间,style按钮
    [self setNotFoundview]; //添加 没有搜索到结果的view
    [self setButtonDetail];  //设置工装,家装按钮的属性
    [self judgeIsselect];  //判断是工装,还是家装页面
    [self getButtonArray]; //获取按钮的个数和属性
    [self loadDataoneFromNet]; //网络获取数据
    [self setFreshview]; //设置上下拉刷新
    _backBlackView = [[UIView alloc]initWithFrame:CGRectMake(0, 104, viewwidth, self.view.frame.size.height-104)];
    _backBlackView.backgroundColor = [UIColor blackColor];
    _backBlackView.alpha = 0.3;
    _backBlackView.hidden = YES;
    [self.view addSubview:_backBlackView];
    
    //添加观察者事件,用来按钮选择反向传值
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(valueChange:) name:@"postValue" object:nil];
   

}

-(void)setFreshview
{
    //创建头部视图
    _headView = [[MJRefreshHeaderView alloc]init];
    _headView.scrollView = _myCllectionView;
    _headView.delegate = self;
    
    //创建尾部视图
    _footView = [[MJRefreshFooterView alloc]init];
    _footView.scrollView = _myCllectionView;
    
    //上下拉刷新,共用一个代理方法
    _footView.delegate = self;
}

//未找到内容视图
-(void)setNotFoundview
{
    _notfoundview = [[NotfoundView alloc]initWithFrame:CGRectMake(0, 200, viewwidth, 120)];
//    _notfoundview.frame = CGRectMake(0, 200, viewwidth, 120);
    [_notfoundview createNotFounddvie];
    [self.view addSubview:_notfoundview];
//    [self.view bringSubviewToFront:_notfoundview];
    _notfoundview.hidden = YES;
    [self.view addSubview:_notfoundview];
}
- (void)valueChange:(NSNotification *)noti
{
    [_dataArray removeAllObjects];
    UIButton *button = noti.object;
    NSInteger num = button.tag/100;
    switch (num) {
        case 1:{
            _buttonSpace1.tag = button.tag;
            NSDictionary *dic = _buttonArray1[button.tag - 100];
            [_buttonSpace1 setTitle:dic[@"name"] forState:UIControlStateNormal];
            [_buttonSpace1 setTitle:dic[@"name"] forState:UIControlStateSelected];
            [self loadDataoneFromNet];
            [_myCllectionView reloadData];
            _buttonSpace1.selected = NO;
        
        }
            break;
        case 2:{
            _buttonSytle.tag = button.tag;
            NSDictionary *dic = _buttonArray2[button.tag - 200];
            [_buttonSytle setTitle:dic[@"name"] forState:UIControlStateNormal];
            [_buttonSytle setTitle:dic[@"name"] forState:UIControlStateSelected];
            [self loadDataoneFromNet];
            [_myCllectionView reloadData];
            _buttonSytle.selected = NO;
    }
            break;
        case 3:{
            _buttonSpace2.tag = button.tag;
            NSDictionary *dic = _buttonArray3[button.tag - 300];
            [_buttonSpace2 setTitle:dic[@"name"] forState:UIControlStateNormal];
            [_buttonSpace2 setTitle:dic[@"name"] forState:UIControlStateSelected];
            [self loadDatatwoFromNet];
            _buttonSpace2.selected = NO;
    }
            break;
            
        default:
            break;
    }
    [self hideViews];
}
//注销观察者
- (void)dealloc
{
    //通知中心观察者不会跟随视图控制器销毁而销毁,需要手动删除
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
//取得空间和style按钮的个数和详情
-(void)getButtonArray
{
    NSString *path = [[NSBundle mainBundle]pathForResource:@"TFilterTypeList.plist" ofType:nil];
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:path];
    
    //这三个button数组中得id存得时nsnumber类型;须要转换
    _buttonArray1 = dic[@"worksHome"][@"space"];
    _buttonArray2 = dic[@"worksHome"][@"style"];
    _buttonArray3 = dic[@"worksPublic"][@"space"];
}

//设置空间和style按钮
-(void)setThreeButton
{
    CGRect Frame1 = CGRectMake(-1, 0, viewwidth/2+1, 39);
    _buttonSpace1 = [UIButton buttonWithTitle:@"全部空间" AndFrame:Frame1];
    [_buttonSpace1 addTarget:self action:@selector(click1:) forControlEvents:UIControlEventTouchUpInside];
    [_view3 addSubview:_buttonSpace1];
    
    CGRect Frame2 = CGRectMake(viewwidth/2-1, 0, viewwidth/2+2, 39);
    _buttonSytle = [UIButton buttonWithTitle:@"全部风格" AndFrame:Frame2];
    [_buttonSytle addTarget:self action:@selector(click2:) forControlEvents:UIControlEventTouchUpInside];
    [_view3 addSubview:_buttonSytle];
    
    
    CGRect Frame3 = CGRectMake(-1, 0, viewwidth+2, 39);
    _buttonSpace2 = [UIButton buttonWithTitle:@"全部空间" AndFrame:Frame3];
    [_buttonSpace2 addTarget:self action:@selector(click3:) forControlEvents:UIControlEventTouchUpInside];
    [_view3 addSubview:_buttonSpace2];
    
    _buttonSpace1.tag = 100;
    _buttonSytle.tag = 200;
    _buttonSpace2.tag = 300;
}


//设置家装和工装按钮
-(void)setButtonDetail
{
    _button1.layer.cornerRadius = 15;
    [_button1 setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    [_button1 setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];

    _button2.layer.cornerRadius = 15;
    [_button2 setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    [_button2 setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    
    
    _view1.clipsToBounds = YES;
    _view2.clipsToBounds = YES;
}


//点击家装按钮
- (IBAction)button1click:(id)sender {
    if (_isSelect2) {
        [self hideViews];
        [_dataArray removeAllObjects];
        [self loadDataoneFromNet];
        [_myCllectionView reloadData];
    }
    _isSelect1 = YES;
    _isSelect2 = NO;
    
    [self judgeIsselect];
}
//点击工装按钮
- (IBAction)button2click:(id)sender {
    if (_isSelect1) {
        [self hideViews];
        [_dataArray removeAllObjects];
        [self loadDatatwoFromNet];
        [_myCllectionView reloadData];
    }
    _isSelect2 = YES;
    _isSelect1 = NO;
  
    [self judgeIsselect];
}

//判断是选择工装还是家装
-(void)judgeIsselect
{
    if (_isSelect1) {
        _button1.selected = YES;
        _button2.selected = NO;
        [_button1 setBackgroundColor:[UIColor redColor]];
        [_button2 setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
        [_view3 bringSubviewToFront:_buttonSpace1];
        [_view3 bringSubviewToFront:_buttonSytle];
        _buttonSpace2.selected = NO;
    }else{
        _button2.selected = YES;
        _button1.selected = NO;
        [_button1 setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
        [_button2 setBackgroundColor:[UIColor redColor]];
        [_view3 bringSubviewToFront:_buttonSpace2];
        _buttonSpace1.selected = NO;
        _buttonSytle.selected = NO;
    }
    
    
}

//家装下空间选择按钮
-(void)click1:(UIButton *)button
{
    
    [self hideViews];
    _buttonSpace1.selected = !_buttonSpace1.selected;
    _buttonSytle.selected = NO;
    if (_buttonSpace1.selected) {
        _backBlackView.hidden = NO;
        
        _buttonView = [[SelectButtonView alloc]initWithFrame:CGRectMake(0, 104, viewwidth, 50*_buttonArray1.count+20)];
        [_buttonView addButtonWithButtonArray:_buttonArray1 AndButtontag:_buttonSpace1.tag];
        [self.view addSubview:_buttonView];
    }
}

//家装下style选择按钮
-(void)click2:(UIButton *)button
{
    [self hideViews];
    _buttonSytle.selected = !_buttonSytle.selected;
    _buttonSpace1.selected = NO;
    if (_buttonSytle.selected) {
        _backBlackView.hidden = NO;
        _buttonView = [[SelectButtonView alloc]initWithFrame:CGRectMake(0, 104, viewwidth, 50*_buttonArray2.count+20)];
        [_buttonView addButtonWithButtonArray:_buttonArray2 AndButtontag:_buttonSytle.tag];
        [self.view addSubview:_buttonView];
        

        
    }
    
}

//工装下空间选择按钮
-(void)click3:(UIButton *)button
{
    [self hideViews];
    _buttonSpace2.selected = !_buttonSpace2.selected;
    if (_buttonSpace2.selected) {
        _backBlackView.hidden = NO;
        _buttonView = [[SelectButtonView alloc]initWithFrame:CGRectMake(0, 104, viewwidth, 50*_buttonArray3.count+20)];
        [_buttonView addButtonWithButtonArray:_buttonArray3 AndButtontag:_buttonSpace2.tag];
        [self.view addSubview:_buttonView];
    }
}

-(void)hideViews
{
    [_buttonView removeFromSuperview];
    _backBlackView.hidden = YES ;
}
//家装信息请求
-(void)loadDataoneFromNet
{
    _notfoundview.hidden = YES;
    NSDictionary *dic = _buttonArray1[_buttonSpace1.tag-100];
    NSDictionary *dic1 = _buttonArray2[_buttonSytle.tag-200];
    NSNumber *num = dic[@"id"];
    NSInteger space = num.integerValue;
    num = dic1[@"id"];
    NSInteger style = num.integerValue;
    
    [[HttpRequestManager shareInstnce]getSecondInfoPage:_page AndSpace:space AndStyle:style Success:^(id responseObjec) {
        NSArray *arr = responseObjec;
        for (NSDictionary *dic in arr) {
            DesighModel *model = [[DesighModel alloc]init];
            model.name = dic[@"name"];
            model.imgViewurl = dic[@"imgUrl"];
            NSNumber *num = dic[@"id"];
            model.numberid = num.stringValue;
            [_dataArray addObject:model];

        }
        if (_dataArray.count ==0) {
            _notfoundview.hidden = NO;
        }
        [_myCllectionView reloadData];
        
    } AndFailure:^(NSError *error) {
        NSLog(@"error == %@",error);
        
    }];
}
//工装信息请求
-(void)loadDatatwoFromNet
{
    _notfoundview.hidden = YES;
    NSDictionary *dic = _buttonArray3[_buttonSpace2.tag-300];
    NSNumber *num = dic[@"id"];
    NSInteger space = num.integerValue;
    
    [[HttpRequestManager shareInstnce]getSecondInfoPage:_page AndSpace:space Success:^(id responseObjec) {
        
        NSArray *arr = responseObjec;
        for (NSDictionary *dic in arr) {
            DesighModel *model = [[DesighModel alloc]init];
            model.name = dic[@"name"];
            model.imgViewurl = dic[@"imgUrl"];
            NSNumber *num = dic[@"id"];
            model.numberid = num.stringValue;
            [_dataArray addObject:model];
        }
        if (_dataArray.count ==0) {
            _notfoundview.hidden = NO;
        }
        [_myCllectionView reloadData];
    } AndFailure:^(NSError *error) {
        
        NSLog(@"error == %@",error);
    }];
}

#pragma mark - UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return  _dataArray.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CollectionViewCell" forIndexPath:indexPath];
    
    cell.imgview.image = nil;
    DesighModel *model = _dataArray[indexPath.row];
    [cell.imgview setImageWithURL:[NSURL URLWithString:model.imgViewurl]];
    cell.imgview.tag = 100 + indexPath.row;
    //图片添加手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clicktap:)];
    [cell.imgview addGestureRecognizer:tap];
    cell.imgview.userInteractionEnabled = YES;
    return  cell;
}

-(void)clicktap:(UITapGestureRecognizer *)tap
{
    [self performSegueWithIdentifier:@"detail3" sender:tap];
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"detail3"]) {
        SecondScrollDetailViewController *view = segue.destinationViewController;
        UITapGestureRecognizer *tap = sender;
        DesighModel *model = _dataArray[tap.view.tag-100];
        view.index = (int)tap.view.tag - 100;
        view.array = _dataArray;
        view.numberid = model.numberid;
    }
}

#pragma mark -MJRefreshBaseViewDelegate


//开始刷新
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    if (refreshView == _headView)
    {
        NSLog(@"下拉刷新");
        _isDragDown = YES;
        _page = 1;
    }else
    {
        NSLog(@"上拉加载更多");
        _isDragDown = NO;
        _page ++;
    }
    
    //2秒钟之后,执行refreshEnd方法
    [self performSelector:@selector(refreshEnd:) withObject:refreshView afterDelay:2.0];
}
//刷新结束
- (void)refreshEnd:(MJRefreshBaseView *)refreshView
{
    //停止刷新,收回视图
    [refreshView endRefreshing];
    //重新填充数据
    [self loadData];
}
-(void)loadData
{
    if (_isDragDown) {
        [_dataArray removeAllObjects];
        if (_isSelect1) {
            [self loadDataoneFromNet];
        }else
        {
            [self loadDatatwoFromNet];
        }
    }
    else
    {
        if (_isSelect1) {
            [self loadDataoneFromNet];
        }else
        {
            [self loadDatatwoFromNet];
        }
    }
}

//- (void)dealloc
//{
//    //使用完毕,需要释放.要不然会导致崩溃[
//    [_headView free];
//    [_footView free];
//}
@end
